#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <signal.h>
#include "wrap.h"

#define MAXLINE 80
#define SERV_PORT 8000

void sig_pipe(int signo)
{
    printf("%s\n", __FUNCTION__);
    return;
}

int main(int argc, char **argv)
{
    struct sockaddr_in serv_addr;
    char buf[MAXLINE];
    int sock_fd, n;
    struct sigaction new_act, old_act;

    new_act.sa_handler = sig_pipe;
    sigemptyset(&new_act.sa_mask);
    new_act.sa_flags = 0;
    sigaction(SIGPIPE, &new_act, &old_act);

    sock_fd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
    serv_addr.sin_port = htons(SERV_PORT);

    Connect(sock_fd, (struct sockaddr *)&serv_addr, \
            sizeof(serv_addr));

    while (fgets(buf, MAXLINE, stdin) != NULL) {
        Write(sock_fd, buf, strlen(buf));
        n = Read(sock_fd, buf, MAXLINE);
        if (n == 0) {
            printf("server colsed.\n");
            break;
        } else
            Write(STDOUT_FILENO, buf, n);
    }
    
    sigaction(SIGPIPE, &old_act, NULL);
    Close(sock_fd);
    return 0;
}

